//
//  CXStackView.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/27.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit

@available(iOS 9.0, *)
//自定义协议 必须遵守一个基协议
protocol CXToolBarDelegate: NSObjectProtocol {
    
    func composeBarButtonDidClick(type: CXToolButtonType)
}

class CXStackView: UIStackView {
    /// 代理
    weak var delegate: CXToolBarDelegate?
    /// 是否为系统样式键盘
    var isSystemKB: Bool = true {
        
        didSet {
            let button = self.viewWithTag(CXToolButtonType.Emotion.rawValue)! as! UIButton
            var iconName = "compose_keyboardbutton_background"
            if isSystemKB {
                iconName = "compose_emoticonbutton_background"
            }
            button.setImage(UIImage(named: iconName), forState: .Normal)
            button.setImage(UIImage(named: "\(iconName)_highlighted"), forState: .Highlighted)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
// MARK: - 布置UI
@available(iOS 9.0, *)
extension CXStackView {
    
    private func setupUI() {
    
        //将stackView的分布方式改为相等布局
        distribution = .FillEqually
        
        addToolButton("compose_toolbar_picture", type: .Picture)
        addToolButton("compose_mentionbutton_background", type: .Mention)
        addToolButton("compose_trendbutton_background", type: .Trend)
        addToolButton("compose_emoticonbutton_background", type: .Emotion)
        addToolButton("compose_add_background", type: .Add)
    }
    
    private func addToolButton(imageName: String, type: CXToolButtonType) {
        
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: .Normal)
        //屏蔽掉系统样式高亮的另外一种方式
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: .Highlighted)
        
        button.setImage(UIImage(named: imageName), forState: .Normal)
        button.setImage(UIImage(named: "\(imageName)_highlighted"), forState: .Highlighted)
        //更新按钮的tag 给按钮添加点击事件
        button.tag = type.rawValue
        button.addTarget(self, action: "btnDidClick:", forControlEvents: .TouchUpInside)
        //将按钮加入stackView
        addArrangedSubview(button)
    }
}
@available(iOS 9.0, *)
extension CXStackView {
    
    @objc private func btnDidClick(button: UIButton) {
        //TODO:添加点击事件
        delegate?.composeBarButtonDidClick(CXToolButtonType(rawValue: button.tag)!)
    }
}
enum CXToolButtonType: Int {
    case Picture = 0
    case Mention = 1
    case Trend = 2
    case Emotion = 3
    case Add = 4
}